package br.com.univas.si6.sd1.jogo.server;

import java.io.BufferedWriter;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;

import br.com.univas.si6.sd1.jogo.client.ClientPlayer;

public class ResultSender {

	private static ResultSender instance = null;
	private ServerPlayer[] players = new ServerPlayer[2];

	private ResultSender() {
		// singletone
	}

	public static ResultSender getInstance() {
		if (instance == null) {
			instance = new ResultSender();
		}
		return instance;
	}

	public void addPlayer(ServerPlayer player) {
		if (players[0] == null) {
			players[0] = player;
		} else if (players[1] == null) {
			players[1] = player;
			enviaJogadas();
			players = new ServerPlayer[2];
		}
	}

	private void enviaJogadas() {
		try {

			ObjectOutputStream player1Stream = new ObjectOutputStream(players[0].getSocket().getOutputStream());
			ObjectOutputStream player2Stream = new ObjectOutputStream(players[1].getSocket().getOutputStream());
			player1Stream.writeObject(new ClientPlayer(players[1].getNome(), players[1].getEscolha()));
			player2Stream.writeObject(new ClientPlayer(players[0].getNome(), players[0].getEscolha()));

		} catch (Exception e) {
			e.printStackTrace();
		}

	}



	private void sendMessage(String message) {
		try {

//			ObjectOutputStream player1Stream = new ObjectOutputStream(players[0].getSocket().getOutputStream());
//			ObjectOutputStream player2Stream = new ObjectOutputStream(players[1].getSocket().getOutputStream());
//			
			ServerPlayer player1 = players[0];
			ServerPlayer player2 = players[1];
			
			
			PrintWriter out1 = new PrintWriter(player1.getSocket().getOutputStream());
			out1.write(message);
			
			PrintWriter out2 = new PrintWriter(player2.getSocket().getOutputStream());
			out2.write(message);
			
//			player1Stream.write(message.getBytes(),0,message.length());
//			player2Stream.write(message.getBytes(),0,message.length());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
